<?php

namespace StudyBuddy\Forms;

use \StudyBuddy\UserAuth;
use \StudyBuddy\Validate;

/**
 * Change password form
 *
 */
class Changepwd extends Form {

    /**
     * Name of form template file
     * The name of actual template should be
     * set in sub-class
     *
     * @var string
     */
    protected $template = 'tplFormchangepwd';

    protected function doValidate() {
        $this->validatePassword()
                ->validateNewPassword()
                ->comparePasswords();
    }

    protected function init() {

        $this->setVar('submit', $this->Tr['Save']);
        $this->setVar('forgot', $this->Tr['Forgot password?']);

        $this->setVar('current_l', $this->Tr['Current Password']);
        $this->setVar('pwd1_l', $this->Tr['Enter new password']);
        $this->setVar('pwd2_l', $this->Tr['Confirm new password']);
        $this->setVar('current_d', $this->Tr['Enter your current password']);
    }

    /**
     * validate current password
     *
     * @return object $this
     */
    protected function validatePassword() {
        $current = $this->getSubmittedValue('current');

        try {
            $oCheckLogin = new UserAuth($this->oRegistry);
            $oUser = $oCheckLogin->validateLogin($this->oRegistry->Viewer->username, $current);
        } catch (\StudyBuddy\LoginException $e) {
            $this->setError('current', $this->_('This is not the correct password'));
        }

        return $this;
    }

    /**
     * Validate that password is valid
     * according to rules set in Validate::enforcePwd
     * 
     * @return $this
     */
    protected function validateNewPassword() {
        $pwd1 = $this->getSubmittedValue('pwd1');
        if (false === Validate::enforcePwd($pwd1)) {
            $this->setError('pwd1', $this->_('Password must be at least 6 characters long and contain at least one number'));
        }

        return $this;
    }

    /**
     * Make sure new password typed the same
     * as confirm new password
     *
     * @return object $this
     */
    protected function comparePasswords() {
        $pwd1 = $this->getSubmittedValue('pwd1');
        $pwd2 = $this->getSubmittedValue('pwd2');

        if ($pwd1 !== $pwd2) {
            $this->setFormError($this->_('"New password" and "Confirm new password" do not match'));
        }

        return $this;
    }

}
